<template>
  <div class="page-register">
    <article class="header">
      <header>
        <a href="/">
          <img :src="logoUrl" class="site-logo" alt="乐鲜" />
        </a>
        <span class="login">
          <em class="bold">已有乐鲜账号？</em>
          <a href="/login">
            <el-button type="primary" size="small">登录</el-button>
          </a>
        </span>
      </header>
    </article>
    <section>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="ruleForm.pwd" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="cpwd">
          <el-input v-model="ruleForm.cpwd" type="password" />
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model="ruleForm.telephone" />
          <el-button
            size="mini"
            round
            @click="sendMsg"
            v-if="statusMsg"
            disabled
            >发送验证码</el-button
          >
          <el-button size="mini" round @click="sendMsg" v-else
            >发送验证码</el-button
          >
          <span class="status">{{ statusMsg }}</span>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" maxlength="4" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register"
            >同意以下协议并注册</el-button
          >
          <div class="error">{{ error }}</div>
        </el-form-item>
        <el-form-item>
          <a
            class="f1"
            href="http://www.meituan.com/about/terms"
            target="_blank"
            >《乐鲜网用户协议》</a
          >
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>

<script>
//import CryptoJS from "crypto-js";
export default {
  data() {
    const self = this;
    const validatorusername = function(rule, value, callback) {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else if (!/^[a-zA-Z][a-zA-Z0-9_.@~!?]{4,16}$/.test(value)) {
        callback(new Error("要求5到17位字符由字母开头、数字及英文组合"));
      } else {
        callback();
      }
    };
    const validatorcpwd = function(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== self.ruleForm.pwd) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    const validatortelephone = function(rule, value, callback) {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      logoUrl: require("@/assets/img/logo-h.png"),
      statusMsg: "",
      error: "",
      ruleForm: {
        username: "",
        code: "",
        pwd: "",
        cpwd: "",
        telephone: ""
      },
      rules: {
        username: [
          {
            required: true,
            type: "string",
            message: "请输入用户名",
            trigger: "blur"
          },
          {
            validator: validatorusername,
            trigger: "blur"
          }
        ],
        telephone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            validator: validatortelephone,
            trigger: "blur"
          }
        ],
        pwd: [
          {
            required: true,
            message: "创建密码",
            trigger: "blur"
          }
        ],
        cpwd: [
          {
            required: true,
            message: "确认密码",
            trigger: "blur"
          },
          {
            validator: validatorcpwd,
            trigger: "blur"
          }
        ]
      }
    };
  },
  layout: "blank",
  methods: {
    sendMsg: function() {
      const self = this;
      let usernamePass;
      let telephonePass;
      let cpwdPass;
      if (self.timerid) {
        return false;
      }
      this.$refs["ruleForm"].validateField("username", valid => {
        usernamePass = valid;
      });
      this.$refs["ruleForm"].validateField("cpwd", valid => {
        cpwdPass = valid;
      });
      self.statusMsg = "";
      if (usernamePass || cpwdPass) {
        return false;
      }
      this.$refs["ruleForm"].validateField("telephone", valid => {
        telephonePass = valid;
      });
      if (!usernamePass && !cpwdPass && !telephonePass) {
        self.$axios
          .get("sso/getAuthCodeForRegis", {
            //userusername: encodeURIComponent(self.ruleForm.username),
            params: { telephone: self.ruleForm.telephone }
          })
          .then(({ status, data }) => {
            if (status === 200 && data && data.code === 200) {
              let count = 60;
              self.statusMsg = `验证码已发送,剩余${count--}秒`;
              self.timerid = setInterval(function() {
                self.statusMsg = `验证码已发送,剩余${count--}秒`;
                if (count === 1) {
                  clearInterval(self.timerid);
                  self.statusMsg = "";
                }
              }, 1000);
            } else {
              self.statusMsg = data.msg;
            }
          });
      }
    },
    register: function() {
      let self = this;
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          self.$axios
            .post("/sso/register", {
              username: self.ruleForm.username,
              password: self.ruleForm.pwd,
              telephone: self.ruleForm.telephone,
              authCode: self.ruleForm.code
            })
            .then(({ status, data }) => {
              if (status === 200) {
                if (data && data.code === 200) {
                  this.$message({
                    message: "注册成功，即将跳转至登录界面",
                    type: "success"
                  });
                  location.href = "/login";
                } else {
                  self.error = data.message;
                }
              } else {
                self.error = `服务器出错，错误码:${status}`;
              }
              setTimeout(function() {
                self.error = "";
              }, 1500);
            });
        }
      });
    }
  }
};
</script>

<style lang="scss">
@import "~@/assets/css/register/index.scss";
</style>
